using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Medianamik.Core.Urls;
using Medianamik.Core;
using System.Globalization;

namespace Medianamik.UI.Services
{
    /// <summary>
    /// Summary description for UrlsService
    /// </summary>
    [WebService(Namespace = "http://absolunet.com/medianamik/webservices/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class UrlsService : System.Web.Services.WebService
    {
        private static IUrlDictionary _urls;
        protected static IUrlDictionary Urls
        {
            get
            {
                return _urls
                    ?? (_urls = new ObjectFactory<IUrlDictionary>().Get());
            }
        }

        [WebMethod]
        public string[] GetUrls(Guid pNodeId, string pCultureName)
        {
            var culture = CultureInfo.GetCultureInfo(pCultureName );
            return Urls.GetEntries(pNodeId, culture)
                .Select(u => u.RequestedPath )
                .Distinct()
                .ToArray();
        }

        [WebMethod]
        public string GetUrl(Guid nodeId, string cultureName, string anchor, string protocol)
        {
            var result = "";
            var culture = CultureInfo.GetCultureInfo(cultureName);
            var url = Urls.GetEntries(nodeId, culture).FirstOrDefault();

            if (url == null) return "";

            if (protocol == "http" || protocol == "https")
            {
                result = url.RequestedUrl.ToString();
                result = result.Substring(result.IndexOf(':'), result.Length - result.IndexOf(':'));

                if (protocol == "http")
                    result = "http" + result;
                else
                    result = "https" + result;
            }
            else
            {
                result = url.RequestedPath;
            }

            if (!String.IsNullOrEmpty(anchor))
                result += "#" + anchor;

            return result;
        }
    }
}
